﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;

namespace NServiceBus.Management.EndpointExplorer
{
    public class EndpointExplorerModel
    {
        private SynchronisedObservableCollection<Endpoint> endpoints;
        private Endpoint selectedEndpoint;
       // private IDictionary<string,Type> mess = new Dictionary<string,Type>();
        private SynchronisedObservableCollection<Type> messages;

        public EndpointExplorerModel()
        {
            messages = new SynchronisedObservableCollection<Type>(new ObservableCollection<Type>());
            //foreach (string m in mess)
            //    messages.Add(m);
        }

        public IList MessageAssemblies
        {
            set
            {
                foreach (Assembly assembly in value)
                {
                    AddMessagesFromAssembly(assembly);
                }
            }
        }

        public void AddMessagesFromAssembly(Assembly assembly)
        {
            foreach (Type t in assembly.GetTypes())
            {
                if (typeof(IMessage).IsAssignableFrom(t) && !t.IsAbstract)
                {
         //           mess.Add(t.Name);
                    messages.Add(t);
                }
            }
        }

        public SynchronisedObservableCollection<Type> Messages
        {
            get
            {
                if (messages == null)
                    messages = new SynchronisedObservableCollection<Type>(new ObservableCollection<Type>());

                return messages;
            }
        }

        //public IList<string> Mess
        //{
        //    get
        //    {
        //        if (mess == null)
        //            mess = new List<string>();

        //        return mess;
        //    }
        //}

        public SynchronisedObservableCollection<Endpoint> Endpoints
        {
            get
            {
                if (endpoints == null)
                    endpoints = new SynchronisedObservableCollection<Endpoint>(new ObservableCollection<Endpoint>());

                return endpoints;
            }
        }

        public Endpoint SelectedEndpoint
        {
            get { return selectedEndpoint; }
        }
        
        public void Handle(IList<Endpoint> endpointsUpdate)
        {
            foreach (var endpoint in endpointsUpdate)
            {
                if (!endpoints.Contains(endpoint))
                {
                    endpoints.Add(endpoint);
                }
            }
        }

        public void SelectedEndpointChanged(Endpoint endpoint)
        {
            selectedEndpoint = endpoint;
        }
    }

}
